import { NameSpace } from 'utils';
import { getAdminList, deleteAdmin, addAdmin } from 'api/index.js';
import { Message } from '@teamix/ui';
import exceed from 'utils/apimap';
import intl from '../../../../../../../../../locale';

const ns = NameSpace('SPACE_SETTING_ADMIN');
export const UPDATE_DATA = ns('UPDATE_DATA');
const { organization } = window.FORCE;

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

// 获取列表数据
export function getList(id) {
  return (dispatch) => {
    updateData({
      isLoadingTable: true,
    })(dispatch);
    getAdminList(id)
      .then((res) => {
        updateData({
          adminList: res.slice(1),
          isLoadingTable: false,
        })(dispatch);
      })
      .catch(() => {
        updateData({
          isLoadingTable: false,
        })(dispatch);
      });
  };
}

// 移除管理员
export function remove(adminId) {
  return (dispatch) => {
    deleteAdmin(adminId).then(() => {
      // updateData({
      //   adminList: res.slice(1),
      //   isLoadingTable: false,
      // })(dispatch);
      Message.success({
        title: intl.get({
          id: 'code-assets.admins.actions.RemovedSuccessfully',
          defaultMessage: '移除成功',
        }),
      });

      dispatch(getList());
    });
  };
}

// 添加管理员
export function addOneAdmin(formData) {
  return (dispatch) => {
    addAdmin(formData).then(() => {
      Message.success({
        title: intl.get({
          id: 'code-assets.admins.actions.AddedSuccessfully',
          defaultMessage: '添加成功',
        }),
      });

      dispatch(getList());
    });
  };
}

// 获取管理员同步开关设置
export function getAdminSetting() {
  return (dispatch) => {
    updateData({
      isGetSetting: true,
    })(dispatch);
    exceed
      .fetch({
        api: 'organization.admin_setting',
        params: {
          orgId: organization.id,
        },
      })
      .then((result) => {
        updateData({
          auto_sync_member_enable: result.auto_sync_member_enable,
          isGetSetting: false,
        })(dispatch);
      });
  };
}

// 获取管理员同步开关设置
export function updateAdminSetting(auto_sync_member_enable) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'organization.admin.sync.enable',
        params: {
          orgId: organization.id,
        },

        data: {
          auto_sync_member_enable,
        },
      })
      .then(() => {
        updateData({
          auto_sync_member_enable,
        })(dispatch);
        Message.success({
          title: auto_sync_member_enable
            ? intl.get({
                id: 'code-assets.admins.actions.AnEnterpriseAdministratorHasBeen',
                defaultMessage: '已开启同步云效企业管理员',
              })
            : intl.get({
                id: 'code-assets.admins.actions.ClosedWithBuyunEffectEnterprise',
                defaultMessage: '已关闭同步云效企业管理员',
              }),
        });
      });
  };
}
